/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.camachosanchez.gui;

import com.camachosanchez.bean.Egresos;
import com.camachosanchez.bean.Pilotos;
import com.camachosanchez.bean.Usuarios;
import com.camachosanchez.controler.jpa.EgresosJpaController;
import com.camachosanchez.controler.jpa.PilotosJpaController;
import com.camachosanchez.controler.jpa.exceptions.IllegalOrphanException;
import com.camachosanchez.controler.jpa.exceptions.NonexistentEntityException;
import com.camachosanchez.gui.table.RenderizadorTabla;
import com.camachosanchez.gui.table.TableSorter;
import com.camachosanchez.util.Constantes;
import com.camachosanchez.util.GUIUtil;
import com.camachosanchez.util.ReportUtil;
import com.camachosanchez.util.SQLUtil;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;
import javax.swing.event.InternalFrameEvent;
import javax.swing.table.DefaultTableModel;
import net.coderazzi.filters.gui.TableFilterHeader;

/**
 *
 * @author ZULLY
 */
public class BusquedaEgresos extends javax.swing.JInternalFrame {

    private DefaultTableModel dm;
    private RenderizadorTabla render;

    /**
     * Creates new form BusquedaEgresos
     */
    public BusquedaEgresos() {
        initComponents();
        setFrameIcon(new ImageIcon(getClass().getResource("/com/camachosanchez/recursos/table.png")));
        Date fechaActual = new Date();
        dateHasta.setDate(fechaActual);
        Calendar cal = new GregorianCalendar();
        cal.setTimeInMillis(fechaActual.getTime());
        cal.add(Calendar.DATE, -30);
        dateDesde.setDate(new Date(cal.getTimeInMillis()));
        String[] tipos = {null, "Vigilante", "Llantas"};
        cmbTipo.setModel(new DefaultComboBoxModel(tipos));

        dm = new DefaultTableModel() {

            @Override
            public boolean isCellEditable(int row, int col) {
                return false;
            }

            @Override
            public Class getColumnClass(int c) {
                return String.class;
            }
        };
        dm.setDataVector(new Object[][]{}, new Object[]{"", "ID", "FECHA", "TIPO", "PILOTO", "UNIDAD", "MONTO"});
        TableSorter tableSorter = new TableSorter(dm, tabla.getTableHeader());
        tabla.setModel(tableSorter);
        TableFilterHeader filterHeader = new TableFilterHeader();
        filterHeader.setTable(tabla);
        tabla.getTableHeader().setReorderingAllowed(false);
        ocultarColumnaCodigo();
        render = new RenderizadorTabla();
        tabla.setDefaultRenderer(String.class, render);
        this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        this.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter() {

            @Override
            public void internalFrameClosing(InternalFrameEvent e) {
                cerrar();
            }
        });
        Usuarios user = Constantes.currentUser;
        if (user.getRol() == Constantes.ROL_ADMINISTRADOR) {
            btnAnular.setVisible(true);
            jSeparator1.setVisible(true);
        } else {
            btnAnular.setVisible(false);
            jSeparator1.setVisible(false);
        }
    }

    private void ocultarColumnaCodigo() {
        GUIUtil.SetAnchoColumnas(tabla);
        tabla.getColumnModel().getColumn(1).setMinWidth(0);
        tabla.getColumnModel().getColumn(1).setMaxWidth(0);
        tabla.getColumnModel().getColumn(1).setPreferredWidth(0);
    }

    public void llenarListasDesplegables() {
        PilotosJpaController dao_piloto = new PilotosJpaController(null);
        List<Pilotos> pilotos = dao_piloto.findPilotosEntities();
        pilotos.add(0, null);
        cmbPiloto.setModel(new DefaultComboBoxModel(pilotos.toArray()));
    }

    private void cerrar() {
        GUIUtil.maximizarTodasLasVentanas(this);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        toolBarPrincipal = new javax.swing.JToolBar();
        jLabel1 = new javax.swing.JLabel();
        btnImprimir = new javax.swing.JButton();
        jSeparator7 = new javax.swing.JToolBar.Separator();
        btnExportarExcel = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        btnAnular = new javax.swing.JButton();
        pnlContenedor = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        dateDesde = new com.toedter.calendar.JDateChooser();
        jLabel4 = new javax.swing.JLabel();
        dateHasta = new com.toedter.calendar.JDateChooser();
        jLabel3 = new javax.swing.JLabel();
        cmbTipo = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        cmbPiloto = new javax.swing.JComboBox();
        btnBuscar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabla = new javax.swing.JTable();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle(".:: Búsqueda de Egresos ::.");

        toolBarPrincipal.setBackground(new java.awt.Color(255, 255, 255));
        toolBarPrincipal.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        toolBarPrincipal.setFloatable(false);
        toolBarPrincipal.setRollover(true);
        toolBarPrincipal.setPreferredSize(new java.awt.Dimension(593, 30));

        jLabel1.setText(" ");
        toolBarPrincipal.add(jLabel1);

        btnImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/16_detail.png"))); // NOI18N
        btnImprimir.setText("Ver detalle");
        btnImprimir.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        btnImprimir.setFocusable(false);
        btnImprimir.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnImprimir.setOpaque(false);
        btnImprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImprimirActionPerformed(evt);
            }
        });
        toolBarPrincipal.add(btnImprimir);
        toolBarPrincipal.add(jSeparator7);

        btnExportarExcel.setBackground(new java.awt.Color(255, 255, 255));
        btnExportarExcel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/excel.png"))); // NOI18N
        btnExportarExcel.setText("Exportar");
        btnExportarExcel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        btnExportarExcel.setFocusable(false);
        btnExportarExcel.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnExportarExcel.setMaximumSize(new java.awt.Dimension(65, 21));
        btnExportarExcel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExportarExcelActionPerformed(evt);
            }
        });
        toolBarPrincipal.add(btnExportarExcel);
        toolBarPrincipal.add(jSeparator1);

        btnAnular.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/16_cancel.png"))); // NOI18N
        btnAnular.setText("Anular");
        btnAnular.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        btnAnular.setFocusable(false);
        btnAnular.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnAnular.setOpaque(false);
        btnAnular.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAnularActionPerformed(evt);
            }
        });
        toolBarPrincipal.add(btnAnular);

        getContentPane().add(toolBarPrincipal, java.awt.BorderLayout.PAGE_START);

        pnlContenedor.setLayout(new java.awt.BorderLayout());

        jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jLabel2.setText("Fecha Inicio:");
        jPanel1.add(jLabel2);

        dateDesde.setDateFormatString("dd/MM/yyyy");
        dateDesde.setMaxSelectableDate(new Date());
        dateDesde.setPreferredSize(new java.awt.Dimension(120, 20));
        dateDesde.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                dateDesdePropertyChange(evt);
            }
        });
        jPanel1.add(dateDesde);

        jLabel4.setText("Fecha Fin:");
        jPanel1.add(jLabel4);

        dateHasta.setDateFormatString("dd/MM/yyyy");
        dateHasta.setMaxSelectableDate(new Date());
        dateHasta.setPreferredSize(new java.awt.Dimension(120, 20));
        jPanel1.add(dateHasta);

        jLabel3.setText("Tipo:");
        jPanel1.add(jLabel3);

        cmbTipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Vigilante", "Llantas" }));
        cmbTipo.setPreferredSize(new java.awt.Dimension(70, 20));
        jPanel1.add(cmbTipo);

        jLabel5.setText("Piloto:");
        jPanel1.add(jLabel5);

        cmbPiloto.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cmbPiloto.setPreferredSize(new java.awt.Dimension(150, 20));
        jPanel1.add(cmbPiloto);

        btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/buscar.png"))); // NOI18N
        btnBuscar.setToolTipText("Buscar");
        btnBuscar.setBorder(null);
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });
        jPanel1.add(btnBuscar);

        pnlContenedor.add(jPanel1, java.awt.BorderLayout.PAGE_START);

        jPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 4, 4, 4));
        jPanel2.setLayout(new java.awt.BorderLayout(5, 5));

        tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        tabla.setRowHeight(22);
        tabla.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(tabla);

        jPanel2.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        pnlContenedor.add(jPanel2, java.awt.BorderLayout.CENTER);

        getContentPane().add(pnlContenedor, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        // TODO add your handling code here:
        buscar();
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void dateDesdePropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_dateDesdePropertyChange
        // TODO add your handling code here:
        if (evt.getPropertyName().compareTo("date") == 0) {
            dateHasta.setMinSelectableDate(dateDesde.getDate());
        }
    }//GEN-LAST:event_dateDesdePropertyChange

    private void btnImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImprimirActionPerformed
        // TODO add your handling code here:
        int fila = tabla.getSelectedRow();
        if(fila > -1){
            final DialogoCargando dlg = new DialogoCargando(Principal.getInstance(), true);
            Thread hilo = new Thread() {

                @Override
                public void run() {
                    try {
                        try {
                            int fila = tabla.getSelectedRow();
                            int id = Integer.parseInt(tabla.getValueAt(fila, 1).toString());
                            EgresosJpaController dao = new EgresosJpaController(null);
                            Egresos egreso = dao.findEgresos(id);
                            ImpresionReportes hojaReporte = new ImpresionReportes(Constantes.REPORTE_EGRESO);
                            Principal.getInstance().getEscritorio().add(hojaReporte);
                            hojaReporte.setVisible(true);
                            hojaReporte.setMaximum(true);
                            hojaReporte.generarReporteEgreso(egreso);
                        } catch (Exception e) {
                            JOptionPane.showMessageDialog(Principal.getInstance(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                        }
                    } finally {
                        dlg.dispose();
                    }
                }
            };
            hilo.start();
            dlg.setVisible(true);
        } else {
            JOptionPane.showMessageDialog(this, "Debe seleccionar un registro de egreso.", "Advertencia", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btnImprimirActionPerformed

    private void btnExportarExcelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExportarExcelActionPerformed
        // TODO add your handling code here:
        DefaultTableModel modeloParaExportacion = new DefaultTableModel() {
            @Override
            public String getColumnName(int columnIndex) {
                switch (columnIndex) {
                    case 0:
                    return "FECHA";
                    case 1:
                    return "TIPO";
                    case 2:
                    return "PILOTO";
                    case 3:
                    return "UNIDAD";
                    case 4:
                    return "MONTO";
                    default:
                    return "";
                }
            }

            @Override
            public int getColumnCount() {
                return 5;
            }
        };
        int numeroFilas = tabla.getRowCount();
        for (int i = 0; i < numeroFilas; i++) {
            Object[] fila = new Object[5];
            for (int j = 2, k = 0; j < 7; j++, k++) {
                fila[k] = tabla.getValueAt(i, j);
            }
            modeloParaExportacion.addRow(fila);
        }
        modeloParaExportacion.setRowCount(numeroFilas);
        try {
            ReportUtil.generarReporteExcel("reportes/egresos_" + GUIUtil.obtenerFechaDDMMYYYHHMMSS() + ".xls", modeloParaExportacion);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_btnExportarExcelActionPerformed

    private void btnAnularActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAnularActionPerformed
        // TODO add your handling code here:
        int fila = tabla.getSelectedRow();
        if(fila > -1){
            if (JOptionPane.showConfirmDialog(null, "¿Está seguro que desea anular el registro de egreso?", "Confirmación", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                int id = Integer.parseInt(tabla.getValueAt(fila, 1).toString());
                EgresosJpaController dao = new EgresosJpaController(null);
                Egresos egreso = dao.findEgresos(id);
                egreso.setAnulado(true);
                try {
                    dao.edit(egreso);
                    JOptionPane.showMessageDialog(this, "El registro de egreso se ha anulado de forma segura.", "Operación finalizada", JOptionPane.INFORMATION_MESSAGE);
                    buscar();
                } catch (IllegalOrphanException ex) {
                    Logger.getLogger(ImpresionReportes.class.getName()).log(Level.SEVERE, null, ex);
                } catch (NonexistentEntityException ex) {
                    Logger.getLogger(ImpresionReportes.class.getName()).log(Level.SEVERE, null, ex);
                } catch (Exception ex) {
                    Logger.getLogger(ImpresionReportes.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "Debe seleccionar un registro de egreso.", "Advertencia", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btnAnularActionPerformed

    private void buscar() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dateDesde.getDate());
        Calendar fechaIni = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
        cal.setTime(dateHasta.getDate());
        Calendar fechaFin = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
        short tipo = 0;
        if (cmbTipo.getSelectedItem() != null) {
            tipo = Short.valueOf(cmbTipo.getSelectedIndex() + "");
        }
        int idPiloto = 0;
        if (cmbPiloto.getSelectedItem() != null) {
            idPiloto = ((Pilotos) cmbPiloto.getSelectedItem()).getId();
        }
        List<Egresos> egresos = SQLUtil.getListaEgresos(fechaIni.getTime(), fechaFin.getTime(), tipo, idPiloto, 0);
        llenarTabla(egresos);
    }

    private void llenarTabla(List<Egresos> lista) {
        SimpleDateFormat formatoDeFecha = new SimpleDateFormat("dd/MM/yyyy");
        Iterator results = lista.iterator();
        dm.setRowCount(0);
        while (results.hasNext()) {
            Egresos egreso = (Egresos) results.next();
            Object[] tupla = new Object[7];
            tupla[0] = "";
            tupla[1] = egreso.getId();
            tupla[2] = formatoDeFecha.format(egreso.getFecha());
            String tipo = "Vigilante";
            if (egreso.getTipo() == Constantes.TIPO_LLANTAS) {
                tipo = "Llantas";
            }
            tupla[3] = tipo;
            tupla[4] = egreso.getIdPilotos().getApellidos() + " " + egreso.getIdPilotos().getNombres();
            tupla[5] = egreso.getIdVehiculos().getPlaca();
            tupla[6] = egreso.getMonto();
            dm.addRow(tupla);
        }
        ocultarColumnaCodigo();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAnular;
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnExportarExcel;
    private javax.swing.JButton btnImprimir;
    private javax.swing.JComboBox cmbPiloto;
    private javax.swing.JComboBox cmbTipo;
    private com.toedter.calendar.JDateChooser dateDesde;
    private com.toedter.calendar.JDateChooser dateHasta;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator7;
    private javax.swing.JPanel pnlContenedor;
    private javax.swing.JTable tabla;
    private javax.swing.JToolBar toolBarPrincipal;
    // End of variables declaration//GEN-END:variables
}
